package com.pandora.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

import com.pandora.assist.Constans;
import com.pandora.exception.UtilException;

public class FileUtil {
	public static File getMaxRoot() {
		File maxUsableSpaceFile=null;
		long maxUsableSpace=0L;
		File[] files=listFileRoot();
		for (File file : files) {
			long usableSpace=file.getUsableSpace();
			if (usableSpace>maxUsableSpace) {
				maxUsableSpace=usableSpace;
				maxUsableSpaceFile=file;
			}
		}
		return maxUsableSpaceFile;
	}
	public static File[] listFileRoot() {
		return File.listRoots();
	}
	public static String getSystemRoot() {
		String classPath=getClassPath();
		return classPath.substring(0,classPath.indexOf(File.separator));
	}
	public static String getClassPath() {
		return FileUtil.class.getResource("/").getPath();
	}
	public static String getWebRoot() throws UtilException {
		return Constans.SYSTEM_WEBROOT;
	}

	/**
	 * 将流保存为文件，路径格式实例如下： 类加载路径classpath:conf/file1.txt
	 * 盘符路径file:D:/conf/file1.txt
	 * 
	 * @param in
	 *            输入流
	 * @param pathname
	 *            保存路径
	 * @throws UtilException
	 */
	public static void saveFile(InputStream in, String pathname)
			throws UtilException {
		File file = getResourcAsFile(pathname);
		saveFile(in, file);
	}
	public static void dropFile(List<String> filePaths) {
		for (String filePath : filePaths) {
			dropFile(filePath);
		}
	}
	public static void dropFile(String filePath) {
		File file=new File(filePath);
		dropFile(file);
	}
	public static void dropFile(File file) {
		if (file.exists()) {
			file.delete();
		}
	}
	public static void dropFiles(List<File> files) {
		for (File file : files) {
			dropFile(file);
		}
	}

	/**
	 * 将流保存为文件
	 * 
	 * @param in
	 * @param file
	 * @throws UtilException
	 * @throws
	 */
	public static void saveFile(InputStream in, File file) throws UtilException {
		if (file.exists()) {
			file.delete();
		}
		OutputStream out;
		try {
			out = new FileOutputStream(file);
		} catch (FileNotFoundException e) {
			throw new UtilException("保存文件失败，目录" + file.getPath() + "无法找到", e);
		}
		byte[] temp = new byte[1024 * 5];
		int length = 0;
		try {
			while ((length = in.read(temp)) > 0) {
				out.write(temp, 0, length);
			}
		} catch (IOException e) {
			throw new UtilException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new UtilException(e);
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					throw new UtilException(e);
				}
			}
		}
	}
	/**
	 * 将文件读取为inputstream 该流使用完后需关闭
	 * @param file
	 * @return
	 * @throws UtilException
	 */
	public static InputStream getResourcAsStream(File file) throws UtilException {
		InputStream in;
		try {
			in = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			throw new UtilException("文件读取失败", e);
		}
		return in;
	}
	/**
	 * 将文件读取为inputstream 该流使用完后需关闭
	 * @param file
	 * @return
	 * @throws UtilException
	 */
	public static InputStream getResourcAsStream(String resourceLocation) throws UtilException {
		File file=getResourcAsFile(resourceLocation);
		return getResourcAsStream(file);
	}
	/**
	 * 将inputstream以指定编码，按字节流读取并转换为字符串返回
	 * @param in 输入流
	 * @param encoding 读取编码
	 * @return 流按指定编码读取并转换后的字符串
	 * @throws UtilException 文件读取时异常或者读取时转码异常
	 */
	public static String fileToString(InputStream in, String encoding)
			throws UtilException {
		StringBuffer content = new StringBuffer();
		BufferedReader bufferedReader;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(in,
					encoding));
		} catch (UnsupportedEncodingException e) {
			throw new UtilException("读取文件时转码错误", e);
		}
		String temp = null;
		int i = 0;
		try {
			while ((temp = bufferedReader.readLine()) != null) {
				if (i++ != 0)
					content.append(Constans.LINE_SEPARATOR);
				temp = new String(temp.getBytes(), Constans.SYSTEM_CHARSET);
				content.append(temp);
			}
		} catch (IOException e) {
			throw new UtilException("文件不是文本，不可行读", e);
		}
		return content.toString();
	}

	/**
	 * 将文件用指定编码读取并转换为字符串
	 * @param file 目标文件
	 * @param encoding 读取编码
	 * @return 按指定编码读取并转换后的字符串
	 * @throws UtilException
	 */
	public static String fileToString(File file, String encoding)
			throws UtilException {
		InputStream in;
		try {
			in = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			throw new UtilException("目标文件不存在", e);
		}
		return fileToString(in, encoding);
	}

	public static File getResourcAsFile(String resourceLocation) throws UtilException {
		URL url = null;
		if (resourceLocation.startsWith("classpath:")) {
			String classPath = resourceLocation
					.substring("classpath:".length());
			url = ClassUtil.getDefaultClassLoader().getResource(classPath);
		}else if (resourceLocation.startsWith("webRoot:")) {
			String projectPath=resourceLocation.substring("webRoot:".length());
			String webRoot=getWebRoot();
			if (StringUtil.isBlank(webRoot)) {
				throw new UtilException("项目根路径获取失败，导致无法获取文件"+"请检查initServlet正确初始化了webapp.root系统变量");
			}
			resourceLocation="file:"+getWebRoot()+projectPath;
			try {
				url = new URL(resourceLocation);
			} catch (MalformedURLException ex2) {
				throw new UtilException("资源文件 [" + resourceLocation
						+ "] 既不是url路径也不是文件路径");
			}
		}else {
			try {
				url = new URL(resourceLocation);
			} catch (MalformedURLException ex2) {
				throw new UtilException("资源文件 [" + resourceLocation
						+ "] 既不是url路径也不是文件路径");
			}
		}
		if (url == null) {
			throw new UtilException("文件 :" + resourceLocation + "不存在");
		} else {
			return getResourcAsFile(url);
		}
	}

	public static File getResourcAsFile(URL url) throws UtilException {
		String urlStr = url.toString();
		String uriStr = StringUtil.replace(urlStr, " ", "%20");
		URI uri = null;
		try {
			uri = new URI(uriStr);
		} catch (URISyntaxException e) {
			throw new UtilException("uri地址语法错误", e);
		}
//		System.out.println(uri.getScheme());
		if (StringUtil.isEqual("file", uri.getScheme())) {
			File file = new File(uri.getSchemeSpecificPart());
			return file;
		} else {
			throw new UtilException(" 无法解析文件路径,因为地址不是一个系统文件路径, "
					+ uri.toString());
		}
	}
}
